<template>
  <!-- 科室领用 -->
  <section>
    <el-page-header @back="goBack" content="科室药品申领"> </el-page-header>
    <br />
    <el-form :model="form" :rules="rules" ref="form" :inline="true">
      <table
        border="0"
        width="100%"
        style="border-spacing: 0;border-collapse: collapse;"
      >
        <tr>
          <td>
            <el-form-item prop="departmentId">
              <!-- <el-select
                v-model="form.deptName"
                clearable
                filterable
                placeholder="请选择领用科室"
              >
                <el-option label="全部" :key="-1" value></el-option>
                <el-option
                  v-for="(item, index) in deptList"
                  :key="index"
                  :value="item.id"
                  :label="item.desc"
                ></el-option>
              </el-select> -->
              <dept :disabled="true" v-model="form.departmentId"></dept>
            </el-form-item>
            <el-form-item prop="doctorId">
              <doctor v-if="form.doctorId" :disabled="true" v-model="form.doctorId"></doctor>
            </el-form-item>
            <el-form-item prop="operatorName">
              <el-input
                v-model="form.operatorName"
                placeholder="请输入领用人"
              ></el-input>
            </el-form-item>
          </td>
        </tr>
      </table>

      <el-table :data="tableList" style="width: 100%">
        <el-table-column label="药品名">
          <template slot-scope="scope">
            {{scope.row.drugName}}
            <span :class="scope.row.highWarning==1?'hight':''">{{scope.row.highWarning==1?'(高危药品)':''}}</span>
            <span class="antibacterial">{{scope.row.antibacterial==1?'(抗菌药物)':'(非抗菌药物)'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="specs" label="规格" width="180">
        </el-table-column>
        <el-table-column label="总量">
          <template slot-scope="scope">
            {{ scope.row.inventoryStatisticVO | durgInventory(dwList) }}
          </template>
        </el-table-column>
        <el-table-column label="领用数量">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <!-- <el-input v-model="scope.row.actualNum" style="flex:1">
              <template slot="append">{{
                scope.row.residueNumUnit | changeAssist(dwList)
              }}</template>
            </el-input>
            <el-input
              style="flex:1"
              v-model="scope.row.actualNum"
              v-if="scope.row.isPiece"
            >
              <template slot="append">{{
                scope.row.residueNumSubsectionUnit | changeAssist(dwList)
              }}</template>
            </el-input> -->
            <el-form-item
              :prop="'applyLogItems.' + scope.$index"
              :rules="numRule"
            >
              <el-input
                v-model.number="form.applyLogItems[scope.$index].actualNum"
                style="flex:1"
              >
                <template slot="append">
                   <el-select style="width:80px;" v-model="form.applyLogItems[scope.$index].applyUnit">
                      <el-option v-for="item in form.applyLogItems[scope.$index].unitList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                   </el-select>
                </template>
              </el-input>
            </el-form-item>
            <!-- <el-form-item
              :prop="'applyLogItems.' + scope.$index"
              :rules="numRule"
            >
              <el-input
                style="flex:1"
                v-model.number="
                  form.applyLogItems[scope.$index].actualNumSubsection
                "
                v-if="scope.row.isPiece == 1"
              >
                <template slot="append">{{
                  scope.row.inventoryStatisticVO.subsectionUnmUnit
                    | changeAssist(dwList)
                }}</template>
              </el-input>
            </el-form-item> -->
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              @click="delDrug(scope.$index)"
              :underline="false"
              type="primary"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-row class="xz_receive_box">
      <el-col :span="24">
        <el-select
          v-model="drug"
          placeholder="请选择选择药品"
          @change="getDrug"
          value-key="id"
          filterable
          remote
          reserve-keyword
          @visible-change="remoteData"
          :remote-method="remoteData"
        >
          <el-option value :key="-1" label>
            <div class="drug_box">
              <span class="drug-item">药品名</span>
              <span class="drug-item">规格</span>
              <span class="drug-item">生产厂家</span>
              <span class="drug-item">库存</span>
            </div>
          </el-option>
          <el-option v-for="item in drugList" :key="item.id" :value="item">
            <div class="drug_box">
              <span class="drug-item">{{ item.drugName }}</span>
              <span class="drug-item">{{ item.specs }}</span>
              <span class="drug-item">{{ item.factory }}</span>
              <span class="drug-item">{{
                item.inventoryStatisticVO | durgInventory(dwList)
              }}</span>
            </div>
          </el-option>
          <pager v-model="pager" @change-pagenum="getData"></pager>
        </el-select>
      </el-col>
    </el-row>
    <br />
    <el-button @click="keepDrug">保存</el-button>
  </section>
</template>
<script>
import vali from "../../../_js/validate";
export default {
  data() {
    return {
      deptList: [], //科室列表
      tableList: [], //选择药品添加的list
      drug: "", //选中药品信息
      drugList: [], //所有入库药品列表
      dwList: [], //药品单位
      form: {
        //领用科室
        departmentId: "",
        //领用医生
        doctorId: "",
        //经办人
        operatorName: "",
        //选中药品
        applyLogItems: [],
      },
      pager:{
        pageNum:1,
        pageSize:20,
        total:0
      },
      rules: {
        doctorId: {
          required: true,
          message: "请选择医生",
          trigger: ["change", "blur"],
        },
        departmentId: {
          required: true,
          message: "请选择科室",
          trigger: ["change", "blur"],
        },
        operatorName: {
          required: true,
          message: "请输入经办人",
          trigger: ["change", "blur"],
        },
      },
      numRule: { trigger: ["blur", "change"], validator: vali.verifyDrugInfo },
    };
  },
  async created() {
    let doctor = await this.$api.getDoctorByToken();
    if(doctor.executed){
      doctor.info?(this.form.doctorId=doctor.info.id,this.form.departmentId=doctor.info.depts[0].deptId):'';
    }
    this.getCommonConfigByKey("药品剂量单位").then((res) => {
      this.dwList = res;
    });
    this.getData();
    // this.form.operatorName = this.adminUser.memberName;
  },
  mounted(){
  },
  methods: {
    getData(query) {
      let json = {
        type: 1,
        source: 1,
        numType: 1,
        queryStr: query,
        // status: 1,
        channel: "MZCF",
      };
      Object.assign(json,this.pager);
      this.$api.pageQueryMedicalDrugInfo(json).then((res) => {
        if (res.executed) {
          this.drugList = res.dataBody.list;
          this.pager.total=res.dataBody.total;
        }
      });
    },
    //移除药品
    delDrug(index) {
      this.form.applyLogItems.splice(index, 1);
      this.tableList.splice(index, 1);
    },
    getDrug(obj) {
      //大单位数量
      obj.actualNum = 0;
      let unitList=[];
      //小单位数量
      obj.applyUnit=obj.medicalDrugSale.packUnit;
      unitList=[{
        id:obj.medicalDrugSale.packUnit,
        name:this.$utils.getDwByDwId(obj.medicalDrugSale.packUnit,this.dwList)
      }]
      obj.isPiece?unitList.push({ id:obj.medicalDrugSale.preparationUnit, name:this.$utils.getDwByDwId(obj.medicalDrugSale.preparationUnit,this.dwList)}):''
      // obj.actualNumSubsection = 0;
      const th = this;
      const drug = function() {
        th.form.applyLogItems.map((it, index) => {
          if (it.id == obj.id) {
            th.form.applyLogItems.splice(index, 1);
          }
        });
        th.form.applyLogItems.push({
          ...obj,
          actualNum: 0,
          applyUnit:obj.medicalDrugSale.packUnit,
          unitList:unitList
        });
      };
      this.form.applyLogItems.length > 0
        ? drug()
        : this.form.applyLogItems.push({
            ...obj,
            actualNum: 0,
            applyUnit:obj.medicalDrugSale.packUnit,
            unitList:unitList
            // actualNumSubsection: 0,
          });
      const fn = function() {
        th.tableList.filter((it, index) => {
          if (obj.id == it.id) {
            th.tableList.splice(index, 1);
          }
        });
        th.tableList.push(obj);
      };
      this.tableList.length > 0 ? fn() : this.tableList.push(obj);
      this.drug = "";
    },
    goBack() {
      this.$router.go(-1);
    },
    remoteData(query){
      this.pager.pageNum=1;
      query=(typeof(query)=='boolean'||query==undefined)?'':query;
      this.getData(query);
    },
    //保存
    keepDrug() {
      this.$refs["form"].validate((v) => {
        if (v) {
          let item = this.form.applyLogItems;
          let arrList = [];
          let json = {};
          item.map((it) => {
            let arr = {
              source: 1,
              sourceId: it.id,
              applyUnit:it.applyUnit,
              applyNum:it.actualNum
            };
            arrList.push(arr);
          });
          Object.assign(json, this.form);
          json.applyLogItems = JSON.stringify(arrList);
          this.$api.addDrugApplyLog(json).then((res) => {
            if (res.executed) {
              this.$message.success("添加成功");
              this.goBack();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    }
  },
  components: {
    dept: () => import("../../_com/deptSearch"),
    doctor: () => import("../../_com/doctorSearch"),
  },
};
</script>
<style scoped>
.xz_receive_box {
  margin-top: 10px;
}
.xz_receive_box .el-select {
  width: 100%;
}
.drug_box {
  display: flex;
}
.drug-item {
  flex: 1;
}
.hight{
  color: #e6a23c;
  margin-left:10px;
}
.antibacterial{
  margin-left:10px;
  color: #409eff;
}
</style>
